<template>
  <div class="organization">
    <div class="organization_treeBg">
      <MetaChoiceList
        ref="organization_list"
        title="部门"
        title-btn="新建"
        :list-data="departmentDataStr"
        @topBtnClick="newRoleBtnClick"
        @editBtnClick="editBtnClick"
        @roloeItemChoose="roloeItemChoose"
        @deleteBtnClick="roleDeleteBtnClick"
        :treeBtn="choiceListTreeBtn"
      />
    </div>
    <div class="organization_infoBg">
      <div class="organization_info">
        <div v-if="Object.keys(roleInfoItem).length > 0" class="organizationO_rightArea">
          <div class="organizationO_infoTitleBg">
            <div class="organizationO_infoTitle">基本信息</div>
          </div>
          <el-form
            ref="org_roleInfo"
            :model="roleInfoItem"
            label-width="120px"
            size="mini"
            label-position="left"
            class="organizationO_info"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="部门名称">
                  <el-col class="organizationO_infoLabel">{{roleInfoItem.name}}</el-col>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门介绍">
                  <el-col class="organizationO_infoLabel">{{roleInfoItem.remark}}</el-col>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <MetaPageTable
            ref="orgUserTable"
            class="orgUserTable"
            table-title="人员列表"
            needCheckbox
            tableHeight="500"
            :need-checkbox="false"
            :is-auto-req="false"
            :tableData="currentUserData"
            :display-item="displayItem"
            :btn-group="btnGroup"
            :line-btn-group="lineBtnGroup"
            @btnClick="tableBtnClick"
            @lineBtnClick="tableInlineBtnClick"
          />
        </div>
      </div>
    </div>
    <el-dialog
      v-if="newDepartmentFlag"
      :title="newDepartmentItem.id && newDepartmentItem.id !== '' ? '编辑部门' : '新建部门'"
      :visible.sync="newDepartmentFlag"
      width="50%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="department_form" :model="newDepartmentItem" label-width="110px" :rules="editRules">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="newDepartmentItem.departmentName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门介绍">
          <el-input v-model="newDepartmentItem.remark" placeholder="请输入部门介绍"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="closeNewDepartmentDialog()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="departmentSave()"
        >保存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="addPersonFlag"
      :title="personInfoItem.id && personInfoItem.id !== '' ? '调整技能' : '添加人员'"
      :visible.sync="addPersonFlag"
      width="50%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="person_form" :model="personInfoItem" label-width="110px" :rules="personRules">
        <el-form-item v-if="personInfoItem.id && personInfoItem.id !== ''" label="人员">
          {{ personInfoItem.name }}
        </el-form-item>
        <el-form-item v-else label="人员" prop="userId">
          <el-select v-model="personInfoItem.userId" placeholder="请选择部门人员">
            <el-option v-for="item in departmentLeftUserList" :key="item.id" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name && item.name !== '' ? item.name : item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修技能" prop="techniqueId">
          <el-select
            v-model="personInfoItem.techniqueId"
            multiple
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="item in alertStatusList"
              :key="item.id"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否短信提醒">
          <el-switch
            v-model="personInfoItem.sendFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item v-if="personInfoItem.sendFlag == '1'" label="短信预警类型">
          <el-select
            v-model="personInfoItem.messageId"
            multiple
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="item in alertStatusList"
              :key="item.id"
              :label="item.value"
              :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="closePersonAddDialog()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="personAddSave()"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import MetaChoiceList from '../components/MetaChoiceList'
import MetaPageTable from '../components/MetaPageTable'
import deepClone from '../utils/deepClone'
import utils from '../utils/utils'
export default {
  name: 'organization',
  components: {
    MetaChoiceList,
    MetaPageTable
  },
  data () {
    var checkName = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入部门名称'))
      }else{
        return callback()
      }
    }
    return {
      roleInfoItem: {},
      departmentDataStr: '',
      choiceListTreeBtn: {
        ifEdit: true,
        ifDelete: true
      },
      newDepartmentItem: {
        departmentName: '',
        remark: ''
      },
      personInfoItem: {
        userId: '',
        name: '',
        techniqueId: [],
        messageId: [],
        sendFlag: '0'
      },
      newDepartmentFlag: false,
      addPersonFlag: false,
      editRules: {
        departmentName: [
          { required: true, validator: checkName, trigger: 'blur' },
          { max: 10, message: '长度少于10个字', trigger: 'blur' }
        ]
      },
      personRules: {
        userId: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ],
        techniqueId: [
          { required: true, message: '请选择维修技能', trigger: 'change' }
        ]
      },
      currentUserData: {},
      displayItem: [
        {
          label: '姓名',
          prop: 'name',
          width: '150'
        },
        {
          label: '用户名',
          prop: 'username',
          width: '150'
        },
        {
          label: '电话',
          prop: 'phone',
          width: '150'
        },
        {
          label: '维修技能',
          prop: 'techniqueName'
        },
        {
          label: '主管',
          prop: 'isLeader',
          type: 'if',
          format: {
            '0': '',
            '1': '是'
          }
        }
      ],
      btnGroup: [{
        id: 'leader',
        title: '任命主管'
      },{
        id: 'add',
        title: '添加人员'
      }],
      lineBtnGroup: [
        {
          id: 'edit',
          title: '修改技能',
        },
        {
          id: 'delete',
          title: '移除'
        }
      ],
      alertStatusList: [],
      departmentLeftUserList: []
    }
  },
  created() {
  },
  mounted() {
    this.initDepartmentList()
    this.getAlertStatus()
    // this.getWholeUserData()
  },
  destroyed() {

  },
  methods: {
    initDepartmentList() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "maintenanceDepartment/getAllList",
        method: "get",
        params: {},
      }).then((res) => {
        if(res.data.code === 200) {
          let departmentData = []
          let currentDataItem = {}
          for(let i in res.data.result) {
            let item = {}
            item = res.data.result[i]
            item.name = res.data.result[i].departmentName
            departmentData.push(item)
            if(Object.keys(this.roleInfoItem).length > 0 && this.roleInfoItem.id === item.id){
              currentDataItem = item
            }
          }
          this.departmentDataStr = JSON.stringify(departmentData)
          if(Object.keys(currentDataItem).length > 0) {
            this.roleInfoItem = deepClone(currentDataItem)
          }else {
            this.roleInfoItem = {}
          }
          this.$nextTick(() => {
            this.$refs.organization_list.setChoiceRole(this.roleInfoItem)

            if(Object.keys(this.roleInfoItem).length > 0) {
              this.getUserList(this.roleInfoItem.id)
            }
          })

        }else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    roloeItemChoose(item) {
      this.roleInfoItem = deepClone(item)
      this.getUserList(this.roleInfoItem.id)
    },
    getUserList(departmentId) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "maintenancePerson/getList?departmentId=" + departmentId,
        method: "get",
        params: {},
      }).then((res) => {
        if(res.data.code === 200) {
          this.currentUserData = {}
          this.currentUserData.page = 1
          this.currentUserData.totalElements = res.data.result.length
          this.currentUserData.content = res.data.result

          this.getLeftUserData()
          this.$nextTick(() => {
            this.$refs.orgUserTable.formDataInit()
          })
        }else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    newRoleBtnClick() {
      this.newDepartmentItem = {
        departmentName: '',
        remark: ''
      }
      this.newDepartmentFlag = true
    },
    editBtnClick(item) {
      this.newDepartmentItem = {
        id: item.id,
        departmentName: item.departmentName,
        remark: item.remark
      }
      this.newDepartmentFlag = true
    },
    closeNewDepartmentDialog() {
      this.newDepartmentFlag = false
    },
    roleDeleteBtnClick(item) {
      this.$confirm('部门一经删除，将无法恢复，是否确认删除？', '确认删除此部门?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {}
        params.id = item.id
        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + "maintenanceDepartment/delete",
          method: "get",
          params: params
        }).then(res => {
          if (res.data.code === 200) {
            this.$notify.success({
              title: "成功",
              message: '部门删除成功',
            });
            this.initDepartmentList()
          }else {
            this.$notify.error({
              title: '错误',
              message: res.data.message
            });
          }
        })
      })
    },
    departmentSave() {
      this.$refs['department_form'].validate((valid) => {
        if (valid) {
          let param = {}
          param.departmentName = this.newDepartmentItem.departmentName
          param.remark = this.newDepartmentItem.remark
          if(this.newDepartmentItem.id && this.newDepartmentItem.id !== '') {
            param.id = this.newDepartmentItem.id
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "maintenanceDepartment/save",
            method: "post",
            data: param,
          }).then((res) => {
            if(res.data.code === 200) {
              this.initDepartmentList()
              this.closeNewDepartmentDialog()
            }else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    tableBtnClick(item) {
      if (item.button === 'add') {
        this.personInfoItem = {
          isLeader: '0',
          userId: '',
          name: '',
          techniqueId: [],
          messageId: [],
          sendFlag: '0'
        }
        this.addPersonFlag = true
      }else if(item.button === 'leader') {
        if(item.rows.length == 0) {
          this.$notify({
            title: '警告',
            message: '请选择需要任命的人员',
            type: 'warning'
          });
          return
        }else if(item.rows.length > 1) {
          this.$notify({
            title: '警告',
            message: '部门主管不可为多人',
            type: 'warning'
          });
          return
        }
        if(item.rows[0].isLeader !== '1') {
          this.$confirm('每个部门只可有一名主管，任命后将自动重置已任命的主管。', '确认任命部门主管?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let params = {}
            params.id = item.rows[0].id
            params.departmentId = this.roleInfoItem.id
            this.$fetch({
              url: process.env.PROGOO_GATE_WATER + "maintenancePerson/updateLeader",
              method: "get",
              params: params
            }).then(res => {
              if (res.data.code === 200) {
                this.$notify.success({
                  title: "成功",
                  message: '任命成功',
                });
                this.getUserList(this.roleInfoItem.id)
              }else {
                this.$notify.error({
                  title: '错误',
                  message: res.data.message
                });
              }
            })
          })
        }
      }
    },
    tableInlineBtnClick(item) {
      if (item.button === 'edit') {
        this.personInfoItem = {
          isLeader: item.rows.isLeader,
          id: item.rows.id,
          userId: item.rows.userId,
          name: item.rows.name,
          techniqueId: [],
          messageId: [],
          sendFlag: item.rows.sendFlag
        }
        this.personInfoItem.techniqueId = item.rows.technique && item.rows.technique !== '' ? item.rows.technique.split(',') : []
        this.personInfoItem.messageId = item.rows.sendType && item.rows.sendType !== '' ? item.rows.sendType.split(',') : []
        this.addPersonFlag = true
      }else if(item.button === 'delete') {
        this.$confirm('确认移除当前人员？', '确认移除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "maintenancePerson/delete?id=" + item.rows.id,
            method: "get",
            params: {},
          }).then((res) => {
            if(res.data.code === 200) {
              this.getUserList(this.roleInfoItem.id)
            }else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        })
      }
    },
    getAlertStatus() {
      let key = 'warningType'
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "domains/getList",
        method: "post",
        data: [key],
      }).then((res) => {
        if(res.data.code === 200) {
          this.alertStatusList = res.data.result[key]
        }else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    getLeftUserData() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + 'maintenancePerson/getUserList',
        method: "post",
        data: {
          page: 1,
          limit: 99999999
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.departmentLeftUserList = res.data.result.content ? res.data.result.content : []
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    personAddSave() {
      this.$refs['person_form'].validate((valid) => {
        if (valid) {
          let param = {}
          param.departmentId = this.roleInfoItem.id
          param.userId = this.personInfoItem.userId
          param.sendFlag = this.personInfoItem.sendFlag
          param.technique = ''
          for(let i in this.personInfoItem.techniqueId) {
            if(param.technique === '') {
              param.technique = this.personInfoItem.techniqueId[i]
            }else {
              param.technique += ',' + this.personInfoItem.techniqueId[i]
            }
          }
          param.sendType = ''
          if(this.personInfoItem.sendFlag == '1') {
            for(let i in this.personInfoItem.messageId) {
              if(param.sendType === '') {
                param.sendType = this.personInfoItem.messageId[i]
              }else {
                param.sendType += ',' + this.personInfoItem.messageId[i]
              }
            }
          }
          param.isLeader = this.personInfoItem.isLeader
          if(this.personInfoItem.id && this.personInfoItem.id !== '') {
            param.id = this.personInfoItem.id
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "maintenancePerson/save",
            method: "post",
            data: param,
          }).then((res) => {
            if(res.data.code === 200) {
              this.getUserList(this.roleInfoItem.id)
              this.closePersonAddDialog()
            }else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    closePersonAddDialog() {
      this.addPersonFlag = false
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.organization{
  width: 100%;
  height: 100%;
  display: flex;
  flex-grow: 1;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .organization_treeBg {
    height: 100%;
  }
  .organization_infoBg {
    height: 100%;
    box-sizing: border-box;
    padding: 0 7px;
    flex: 1;
  }
  .organization_info {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    border: 1px solid rgb(228, 234, 236);
    flex: 1;
    overflow-y: scroll;
    box-sizing: border-box;
    padding: 15px;
    .organizationO_rightArea{
      .orgUserTable {
        float: left;
        width: 100%;
        overflow-y: unset;
        margin-top: 20px;
      }
      .organizationO_infoTitleBg {
        width: 100%;
        float: left;
        // margin-top: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
        .organizationO_infoTitle {
          font-size: 20px;
          float: left;
          height: 30px;
          line-height: 30px;
        }
        .organizationO_delBtn {
          float: right;
        }
      }
      .organizationO_info {
        width: 100%;
        float: left;
        padding-top: 10px;
        padding-bottom: 10px;
        .organizationO_infoLabel {
          color: #606266;
        }
        .organizationO_formItem {
          display: flex;
          align-items: center;
        }
      }
    }
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
